/**
 * 任务限制器
 */
class TaskLimiter {
    limit = 0
    waitQueue = []
    execQueueMap = new Map()
    constructor(limit = 6) {
        this.limit = limit
    }
    _startTask() {
        const { waitQueue, execQueueMap, limit } = this
        while (waitQueue.length && execQueueMap.size < limit) {
            const task = waitQueue.shift()
            execQueueMap.set(task, task)
            const callback = res => {
                execQueueMap.delete(task)
                this._startTask()
                return res
            }
            task().then(callback, callback)
        }
    }
    createLazyTask(fn) {
        const that = this
        const { waitQueue } = this
        return function (...args) {
            return new Promise(resolve => {
                const task = async () => {
                    const p = fn.apply(this, args)
                    resolve(p)
                    return p
                }
                waitQueue.push(task)
                that._startTask()
            })
        }
    }

    push(fn) {
        const task = async () => fn()
        this.waitQueue.push(task)
        this._startTask()
    }
}

export default TaskLimiter